package com.leyantech.ecp.agenx.loadtest.consumer;

import com.leyantech.chaos.kafka.KafkaConsumerStringProcessor;
import com.leyantech.chaos.kafka.KafkaProducerStringClient;
import com.leyantech.ecp.agenx.loadtest.converter.LoadtestMessageConverter;
import com.leyantech.utility.config.ConfigUtil;

import com.google.inject.Inject;
import io.vertx.core.json.JsonObject;
import org.apache.kafka.clients.consumer.ConsumerRecord;

import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-18.
 */
public class MessageConsumer implements KafkaConsumerStringProcessor {

  private final KafkaProducerStringClient producer;

  private final LoadtestMessageConverter loadTestMessageConverter;

  static final Supplier<String> messageTopic = ConfigUtil.getDynamicConfig(
      "connector.message.topic",
      Function.identity(),
      ""
  );

  @Inject
  public MessageConsumer(KafkaProducerStringClient producer,
      LoadtestMessageConverter loadTestMessageConverter) {
    this.producer = producer;
    this.loadTestMessageConverter = loadTestMessageConverter;
  }

  @Override
  public void accept(ConsumerRecord<String, String> consumerRecord) {

    final JsonObject message = new JsonObject(consumerRecord.value());
    final JsonObject loadTestMessage = loadTestMessageConverter.apply(message);

    final String storeId = (String) loadTestMessage.remove("sid");
    final String assistantsId = (String) loadTestMessage.remove("aid");

    final String key = String.join(".", storeId, assistantsId);
    producer.send(messageTopic.get(), key, loadTestMessage.toString());
  }

}
